<!-- 题目管理 -->
<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { reactive, ref, watch } from "vue"
import { Query, Cards } from "./modules/question-bank"
import { getExamQuestionsApi } from "#/api/manage/question-bank"
import { FILL_BLANK } from "./modules/const"
import Pagination from "#/components/pagination.vue"
import { $t } from '@vben/locales';

const queryRef = ref<InstanceType<typeof Query> | null>(null)
interface QueryDataType {
  type: string[];
  stem: string;
  courseId: string;
  chapterId: string;
}
const queryData = reactive<QueryDataType>({
  type: [],
  stem: '',
  courseId: '',
  chapterId: ''
})

const handleModelValueUpdate = (newValue: QueryDataType) => {
  // 安全地更新查询数据，保持响应式
  Object.assign(queryData, {
    type: newValue.type ?? [],
    stem: newValue.stem ?? '',
    courseId: newValue.courseId ?? '',
    chapterId: newValue.chapterId ?? ''
  });
}

const tableData = ref<any>([])
const loading = ref(false)
const pageData = reactive<any>({
  total: 0,
  curPage: 1,
  pageSize: 10
})

const onQuery = () => {
  loading.value = true;
  getExamQuestionsApi({
    ...queryData,
    curPage: pageData.curPage,
    pageSize: pageData.pageSize
  }).then((res) => {
    let { pageInfo, data = [] } = res
    pageData.total = pageInfo.totalRows
    tableData.value.length = 0
    data = data || []
    data.forEach((item: any) => {
      item.isHider = true
      if (item.options) {
        item.options = JSON.parse(item.options)
      }
      //answers
      if (item.answers && item.type == FILL_BLANK) {
        try {
          item.answers = JSON.parse(item.answers)
        } catch (e) {
          item.answers = item.answers
        }
      }
    });
    tableData.value.push(...data)
  }).finally(() => {
    loading.value = false;
  })
}
// 监听分页数据变化，触发查询
watch(() => [pageData.curPage, pageData.pageSize], () => {
  onQuery()
}, { deep: true })

const edit = () => {
  queryRef.value?.onEdit()
}

const handleToggleAllCards = (isCollapsed: boolean) => {
  tableData.value.forEach((item: any) => {
    // isCollapsed为true表示收起，所以要隐藏详情 (isHider = false)
    // isCollapsed为false表示展开，所以要显示详情 (isHider = true)
    item.isHider = !isCollapsed;
  });
}

onQuery()
</script>
<template>
  <Page class="question h-full">
    <div class="question-bank flex flex-col h-full">
      <Query v-model="queryData" class="mb-[0px]" @queryData="onQuery" @update:modelValue="handleModelValueUpdate"
        @toggleAllCards="handleToggleAllCards" ref="queryRef"></Query>
      <Cards v-loading="loading" @queryData="onQuery" v-if="tableData.length" :tableList="tableData"
        :searchKeyword="queryData.stem" class="min-h-[1px] flex-1 bg-[#fff] overflow-auto" @editItem="edit"></Cards>
      <el-empty v-else :description="$t('common.emptyTxt')" class="h-full bg-[#fff]" />
      <Pagination v-model="pageData">
      </Pagination>
    </div>
  </Page>
</template>
